/*
 * @Author       : wfl
 * @LastEditors: fj
 * @description  :
 * @updateInfo   :
 * @Date         : 2022-11-07 16:08:42
 * @LastEditTime: 2023-08-01 09:29:54
 */
import { defineComponent, ref } from 'vue'
import type { Ref } from 'vue'
import IkPageFull from '@g/components/LayoutCom/IkPageFull/index.vue'
import IkSplitPan from '@g/components/LayoutCom/IkSplitPan/index.vue'
import IkPageTabs from '@g/components/LayoutCom/IkPageFull/IkPageTabs.vue'
import IkItemList from '@g/components/BaseCom/IkItemList/index.vue'
import { ikStore } from 'iking-utils'
import { useNews } from '../news-template/useNews'
import { useNews as centerUserNews } from '../useNews'
import IkSvgIcon from '@/global/components/BaseCom/IkSvgIcon/index.vue'
import type { ISearchForm } from '@/global/enums/search'
import { msgApi } from '@/MainApp/apis/msg'
import { REDIRECT } from '@g/store/modules/socket'
import useApproveFlowStore from '@g/store/modules/approveFlow'
import useNotificationStore from '@/global/store/modules/notification'
export interface TList {
  businessKey: string
  businessName: string
  [key: string]: any
}
const personalNews = defineComponent({
  setup() {
    const {
      businessType,
      getBusiness,
      msgBoxWarnAsync,
      msgSuccess,
      msgError
    } = useNews()

    const notificationStore = useNotificationStore()

    const {
      getTableData,
      tableData,
      total,
      pageData,
      loading
    } = centerUserNews()
    const router = useRouter()
    const typeList = computed(() => businessType.value)
    const userInfo = ref(ikStore.local.getItem(ELocal.USER_INFO) ?? '')
    const businessKey = ref('')
    const pageRef = ref()
    const activeLog = ref('NO_READ')
    const tabs = [{ id: 'NO_READ', label: '未读' }, { id: 'READ', label: '已读' }]
    const tableFields: Ref<ISearchForm[]> = ref([{
      key: 'businessName',
      value: '',
      label: '模块',
      show: true,
      minWidth: 100
    }, {
      key: 'messageTitle',
      value: '',
      label: '标题',
      show: true,
      minWidth: 100
    }, {
      key: 'messageContent',
      value: '',
      label: '消息内容',
      show: true,
      minWidth: 300
    }, {
      key: 'operate',
      value: '',
      label: '操作',
      width: 106,
      show: true,
      tableSlot: 'operate',
      align: 'center'
    }])

    // 切换选中消息类型
    const handSelectType = (row: TList) => {
      pageData.value.page = 1
      activeLog.value = 'NO_READ'
      businessKey.value = row.businessKey
      getTableData({ businessKey: businessKey.value, receiverId: userInfo.value.id, readStatus: activeLog.value })
    }

    /**
     * 详情
     */
    const flowStore = useApproveFlowStore()
    const handleDetail = (row: any) => {
      const { redirectTo } = row
      if (redirectTo.startsWith('approve://')) {
        try {
          const splitPath = redirectTo.split('/')
          const tabId = splitPath?.[2]
          const id = splitPath?.[3]
          const redirectObj = REDIRECT.approve
          router.push({ path: redirectObj.path, query: { id: row.id } })
        } catch (error) {

        }
      }
      else {
        router.push({ path: row.redirectTo, query: { link: row.redirectTo } })
      }
    }
    /**
     * 去处理
     */
    const handleComplete = async (row: any) => {
      const { redirectTo } = row
      if (redirectTo.startsWith('approve://')) {
        try {
          const splitPath = redirectTo.split('/')
          const tabId = splitPath?.[2]
          const id = splitPath?.[3]
          const redirectObj = REDIRECT.approve
          const info = { tabId: (redirectObj.value as any)?.[tabId], id }
          flowStore.setSocketInfo({
            path: redirectObj.path,
            ...info
          })
          router.push({ path: redirectObj.path, query: { id: row.id } })
        } catch (error) {

        }
      } else {
        router.push({ path: row.redirectTo, query: { link: row.redirectTo } })
      }
      // 标记已读
      const { msg, success } = await msgApi.markRead(row.id)
      if(success) {
        msgSuccess(msg)
        notificationStore.init()
      }
      // if (success)
      //   msgSuccess(msg)
      // 判断是否系统内地址，并跳转
      // if (row.redirectTo.startsWith('http')) {
      //   window.open(row.redirectTo)
      // }
      // else {
      //   const url = row.redirectTo.split('//')[1]
      //   router.push({ path: url })
      // }
    }
    /**
     * @description: 全部已读
     * @return {*}
     */
    const readAll = async () => {
      msgBoxWarnAsync(
        '消息确认',
        '所有消息状态将置为已读，是否继续？',
        async () => {
          const { success, msg } = await msgApi.markReadAll()
          if (success) {
            msgSuccess(msg)
            getTableData({ businessKey: businessKey.value, receiverId: userInfo.value.id, readStatus: activeLog.value })
          }
          else {
            msgError(msg)
          }
        }
      )
    }
    const tabClick = (e: any) => {
      pageData.value.page = 1
      getTableData({ businessKey: businessKey.value, receiverId: userInfo.value.id, readStatus: e })
    }
    onMounted(() => {
      getBusiness()
    })
    return () => (
      <>
        <IkSplitPan size={0} left-size={[0, 100]}>
          {{
            left: (
              <>
                <IkPageFull
                  header-title="个人消息"
                  refreshBtn={false}
                  settingBtn={false}
                >
                  {{
                    headerRight: (
                      <>
                        <IkSvgIcon
                          show-bg
                          pop
                          width={40}
                          size="big"
                          title="刷新"
                          name="iksvg_shuaxin"
                          onClick={() => getBusiness()}
                        />
                      </>
                    ),
                    table: (
                      <>
                        <IkItemList
                          list={typeList.value as any}
                          proxy={{ label: 'businessName', value: 'businessKey' }}
                          onSelect={(role: any) => handSelectType(role)}
                          isCount={true}
                        >
                        </IkItemList>
                      </>
                    )
                  }}
                </IkPageFull>
              </>
            ),
            right: (
              <IkPageTabs v-model={activeLog.value} tabs={tabs} onTabClick={e => tabClick(e)}>
                <IkPageFull
                  ref={pageRef as any}
                  v-model={pageData.value}
                  fields={tableFields.value}
                  table-data={tableData.value}
                  total={total.value}
                  loading={loading.value}
                  search={() => getTableData({ businessKey: businessKey.value, receiverId: userInfo.value.id, readStatus: activeLog.value })}
                >
                  {{
                    headerRight: () => activeLog.value === 'NO_READ'
                      ? (
                        <el-button type="primary" onClick={() => readAll()}>全部已读</el-button>
                      )
                      : null,
                    operate: ({ data }: { data: any; }) => activeLog.value === 'NO_READ'
                      ? (
                        <div>
                          <IkSvgIcon
                            show-bg
                            title="查看详情"
                            pop
                            start-margin={false}
                            name="iksvg_liebiao"
                            v-role="LOOK_PERSONAL_DETAIL"
                            onClick={() => handleDetail(data.row)}
                          />
                          <IkSvgIcon
                            show-bg
                            pop
                            title="去处理"
                            v-role="PROCESS_PERSONAL_NEWS"
                            name="iksvg_fujian"
                            onClick={() => handleComplete(data.row)}
                          />
                        </div>
                      )
                      : (
                        <IkSvgIcon
                          show-bg
                          title="查看详情"
                          start-margin={false}
                          size="small"
                          name="icon-ziyuanliebiao"
                          v-role="LOOK_PERSONAL_DETAIL"
                          onClick={() => handleDetail(data.row)}
                        />
                      )
                  }}
                </IkPageFull>
              </IkPageTabs>
            )
          }}
        </IkSplitPan >
      </>
    )
  }
})

export default personalNews
